//
//  CYMyQuestionViewController.m
//  cyydt
//
//  Created by chu on 2019/1/21.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYMyQuestionViewController.h"
#import "CYMyQuestionTableViewCell.h"
#import "CYWenDaDetailViewController.h"
#import "CYPubilishQuestionViewController.h"
@interface CYMyQuestionViewController ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@end

@implementation CYMyQuestionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的提问";
//    [self.view addSubview:self.tableView];
    self.tableView.estimatedRowHeight = 44;
    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self getData];
    [self rightBarItemWithTitle:@"提问"];

}

- (void)RighttouchEvent{
    CYPubilishQuestionViewController *wenda = [[CYPubilishQuestionViewController alloc] init];
    [[AppDelegate sharedAppDelegate] pushViewController:wenda];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CYMyQuestionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYMyQuestionTableViewCell"];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"CYMyQuestionTableViewCell" owner:self options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataSourceArr[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00001f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CYMyQuestionModel *model = self.dataSourceArr[indexPath.row];
    if ([model.status integerValue] == 1) {
        CYWenDaDetailViewController *wenda = [[CYWenDaDetailViewController alloc] init];
        wenda.wedaId = [model.ID stringValue];
        [[AppDelegate sharedAppDelegate] pushViewController:wenda];
    }else if([model.status integerValue] == 0){
        [self.view makeToast:@"提问目前处于待审核状态" duration:1.5 position:CSToastPositionCenter];
    }else if([model.status integerValue] == 2){
        CYPubilishQuestionViewController *wenda = [[CYPubilishQuestionViewController alloc] init];
        wenda.wentiId = [model.ID stringValue];
        wenda.type = TiWenType_BoHui;
        [[AppDelegate sharedAppDelegate] pushViewController:wenda];
    }else{
        CYWenDaDetailViewController *wenda = [[CYWenDaDetailViewController alloc] init];
        wenda.wedaId = [model.ID stringValue];
        [[AppDelegate sharedAppDelegate] pushViewController:wenda];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    CYMyQuestionModel *model = self.dataSourceArr[indexPath.row];
    if ([model.status integerValue] == 2) {
        return YES;
    }
    return NO;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 删除
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //只要实现这个方法，就实现了默认滑动删除！！！！！
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // 删除数据
        CYMyQuestionModel *model = self.dataSourceArr[indexPath.row];
        [LEEAlert alert].config
        .LeeHeaderColor([UIColor whiteColor])
        .LeeAddContent(^(UILabel *label) {
            label.font = [UIFont systemFontOfSize:18];
            label.textColor = [UIColor blackColor];
            label.text = @"是否确定删除这条提问";
        }).LeeAddAction(^(LEEAction *action) {
            action.titleColor = RGBOF(0x666666);
            action.borderColor = RGBOF(0xE0DFDF);
            action.title = @"取消";
            
        })
        .LeeAddAction(^(LEEAction *action) {
            action.titleColor = RGBOF(0xF43636);
            action.borderColor = RGBOF(0xE0DFDF);
            action.title = @"确定";
            action.clickBlock = ^{
                [self removeFromServerWithMode:model];
            };
        })
        .LeeShow();
    }
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)deleteSelectModel:(CYMyQuestionModel *)model{
    [self.dataSourceArr removeObject:model];
}

- (void)removeFromServerWithMode:(CYMyQuestionModel *)model{
    NSString *url = [NSString stringWithFormat:@"%@%@/%@",User_HOST, @"ask/question",model.ID];
    [[XBRequest sharedInstance] deleteDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"删除 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                [self deleteSelectModel:model];
                [self.tableView reloadData];
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

#pragma mark - DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"wuneir"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"当前页面没有内容！";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:RGBOF(0x999999)
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    // 空白页面被点击时开启动画，reloadEmptyDataSet
    [self getData];
}

- (void)getData{
    self.page = 1;
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"ask/questions"];
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"首页推荐 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        [self.tableView removeFromSuperview];
        [self.view addSubview:self.tableView];
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSArray *data = responseResult[@"data"];
                [self.dataSourceArr removeAllObjects];
                for (NSDictionary *dic in data) {
                    CYMyQuestionModel *model = [CYMyQuestionModel modelWithDictionary:dic];
                    [self.dataSourceArr addObject:model];
                }
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
        [self.tableView reloadData];

    }];
}

- (void)getMoreData{
    self.page ++;
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"ask/questions"];
    NSDictionary *param = @{@"pageNo":[NSNumber numberWithInteger:self.page]};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"首页推荐 ---- %@",responseResult);
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
            self.page -- ;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSArray *data = responseResult[@"data"];
                for (NSDictionary *dic in data) {
                    CYMyQuestionModel *model = [CYMyQuestionModel modelWithDictionary:dic];
                    [self.dataSourceArr addObject:model];
                }
                [self.tableView reloadData];
            }else{
                self.page -- ;
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, kWindowH - Height_NavBar) style:UITableViewStyleGrouped];
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BackGroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"CYMyQuestionTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYMyQuestionTableViewCell"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getData];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self getMoreData];
        }];
        
    }
    return _tableView;
}

- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

@end
